﻿using Microsoft.AspNetCore.Http;
using System;

namespace Bootstrap.Security.Authorization
{
    /// <summary>
    /// IButtonAuthorization 内部默认实现类
    /// </summary>
    internal class DefaultButtonAuthorization : IButtonAuthorization
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="func">通过指定用户名获取按钮授权集合回调方法</param>
        public DefaultButtonAuthorization(Func<string, string, string, bool> func = null) => _proxy = func;

        private readonly Func<string, string, string, bool> _proxy;

        /// <summary>
        /// 授权方法
        /// </summary>
        /// <param name="context">HttpContext 上下文</param>
        /// <param name="url">当前请求地址 Url</param>
        /// <param name="auths">当前按钮授权字符串键值</param>
        /// <returns></returns>
        public bool Authorizate(HttpContext context, string url, string auths)
        {
            if (context.User.IsInRole("Administrators")) return true;

            var userName = context.User.Identity.Name;
            return _proxy?.Invoke(userName, url, auths) ?? false;
        }
    }
}
